import time
from tokenize import cookie_re

import requests
import re
import os
import pandas as pd
import random


user_agents = [
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3',
        'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36',
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:53.0) Gecko/20100101 Firefox/53.0',
        'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)',
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36',
        # 更多User-Agent字符串...
    ]

def get_random_user_agent():
    return random.choice(user_agents)

""" 获取指定skc的价格 """
def get_price(searchKey,cookie,pageid,setcookie):
    url = "https://us.shein.com/pdsearch/" + searchKey + "/?ici=s1`EditSearch`sm25030400644979431`_fb`d0`PageSearchResult&search_source=1&search_type=all&source=search&src_identifier=st%3D2%60sc%3Dsm25030400644979431%60sr%3D0%60ps%3D1&src_identifier_pre_search=&src_module=search&src_tab_page_id=" + pageid

    headers = {
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
        'Accept-Encoding': 'gzip, deflate, br, zstd',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Cookie': cookie,
        'Priority': 'u=0, i',
        'Referer': 'https://us.shein.com/pdsearch/123/?ici=s1`EditSearch`123`_fb`d0`PageRiskCrawlerBlock&search_source=1&search_type=all&source=search&src_identifier=st%3D2%60sc%3D123%60sr%3D0%60ps%3D1&src_identifier_pre_search=&src_module=search&src_tab_page_id=page_risk_crawler_block1742465950885',
        'Sec-Ch-Ua': '"Chromium";v="134", "Not:A-Brand";v="24", "Google Chrome";v="134"',
        'Sec-Ch-Ua-Mobile': '?0',
        'set-cookie':setcookie,
        'Sec-Ch-Ua-Platform': '"Windows"',
        'Sec-Fetch-Dest': 'document',
        'Sec-Fetch-Mode': 'navigate',
        'Sec-Fetch-Site': 'same-origin',
        'Sec-Fetch-User': '?1',
        'Upgrade-Insecure-Requests': '1',
        'User-Agent': get_random_user_agent()
    }
    print(searchKey)
    time.sleep(10)
    response = requests.get(url, headers=headers)

    # print("Status Code:", response.status_code)
    # print("Response Text:", response.text)


    pattern = r'data-note data-v-ab96641f[^>]*>\s*<span>(.*?)<\/span>'
    match = re.search(pattern, response.text)
    if match:
        extracted_text = match.group(1)
        print(extracted_text)
        return extracted_text
    else:
        print("未找到匹配内容")



"""读取文件，将skc的前端价格写入文件中"""
def editFile(folder_path,cookie,pageid,setcookie):
    for filename in os.listdir(folder_path):
        if filename.endswith('.xlsx'):  # 确保处理的是Excel文件
            file_path = os.path.join(folder_path, filename)

            # 读取Excel文件
            df = pd.read_excel(file_path)

            # 将'前端价格'列的数据类型转换为字符串，以避免类型不兼容的问题
            df['前端价格'] = df['前端价格'].astype(str)

            # 假设'SKC'列包含SKC值，'前端价格'列是我们将要写入价格的列
            for index, row in df.iterrows():
                skc = row['SKC']
                price = get_price(skc,cookie,pageid,setcookie)
                df.at[index, '前端价格'] = price   # 格式化价格并添加货币符号

                # 休眠一段时间，模拟人类操作，避免被检测为爬虫
                time.sleep(1)  # 休眠1秒

            # 将结果写回原始Excel文件
            df.to_excel(file_path, index=False)

            print(f"价格更新完成，结果已保存到 {file_path}")


def edit_price(folder_path,cookie,pageid):
    editFile(folder_path,cookie,pageid)

if __name__ == '__main__':
    cookie = 'armorUuid=20250319151619f5a57b37b7e89d5821ca71a4677dc4b500e15875510f95b300; sessionID_shein=s%3AjGebbAC6OkZ1-K8M85e9NiHyoGzWJg4P.eD1JCznzpKHB2e1mDKN%2B4ZwGt7sj1nWwKHls3RC5BYc; AT=MDEwMDE.eyJiIjo3LCJnIjoxNzQyMzY4NTc5LCJyIjoiZnZHSkU5IiwidCI6MX0.98285dd6d69897d9; privacy-sdk-cookie-id=396CEFDD_E089_8454_9B57_CEE07E043D56; smidV2=20250319151643d1cc58c3314a30523772a27ec406ad4e006b01f764fc64690; _fbp=fb.1.1742368605358.691714171919334725; _scid=z-c-0WNZYv1SWhyxhXjpAdn8-l4d2rqG; _gcl_au=1.1.1594583772.1742368606; ndp_session_id=c38b4728-2ccf-4a96-807b-730865aa7db8; _pin_unauth=dWlkPU1tWXlOV1EwWmpVdE1qYzFPQzAwWkRFM0xXRmtaV1V0WlRjd09ETmtZek0wT0RobA; _ScCbts=%5B%5D; _sctr=1%7C1742313600000; _f_c_llbs_=K1905_1742477776_XeJMTWVZWRiA_lwKwBbLva-iqCoveV5UA27ChIvitoUrfl1fzcO4L1kHx45k9m2QCT0qeZo2AO3XJs29_cW4UgUITM7vhoBGMRy-QQpXW6BksHvAETlgmuS_72S5kEOhwgwP73McIclUxr6ifcPbnTE5yLZpoTQGvuoE8qk0QKpMKXiG6Zx-PInLUVKfVkDfZtfl5SJj5JpEw3Moah5ZIHiA7EyRHkLc8Cc0FRxclvXH4-C4vL7al6ciU2ATOFudj1MysoBuRDNYjOgsKedo2CIBeI8BBjemE2ZdrE7I8gfom8vKYgvSGfmJpB5TkKBitgZkylLk79sQs8gUZeI9Lw; _uetsid=b41084c0057411f0b01893329c3fd610; _uetvid=1d4f3ac0049211f0963c07388c0f840c; cto_bundle=Djcbx19NNHNOTTZ1SW5td2ZkMGpneWk5NXRZVCUyQld2Q01wdUF4SDNiTThNVWF3JTJGM1dLdUhsaGV0STFSRDh6akY1d2o5SG1xOVdDdmlybyUyRmFiQ2FvUTVYV3ZwNXgwU0R0eTZwa1hLY2ZPRiUyRnlQRlBQTFpyU2NOaENHdUNPcnlZOXF1TnY2c0hlekxJOFRQNTJrMlI5T2pZQ05IQSUzRCUzRA; _scid_r=22c-0WNZYv1SWhyxhXjpAdn8-l4d2rqGQGD2YQ; _rdt_uuid=1742368605330.eb6d8361-c09c-4afb-81af-313814b02c15; dicbo_id=%7B%22dicbo_fetch%22%3A1742477770363%7D'
    pageid = "page_risk_crawler_block1742476238688"
    setcookie = 'sessionID_shein=s%3AjGebbAC6OkZ1-K8M85e9NiHyoGzWJg4P.eD1JCznzpKHB2e1mDKN%2B4ZwGt7sj1nWwKHls3RC5BYc; expires=Sat, 22-Mar-2025 01:40:32 GMT; max-age=129600; path=/; HttpOnly; secure'
    editFile("D:/Desk/111",cookie,pageid,setcookie)